const fs = require('fs')
const path = require('path')
const logger = require('../../util/logger')

const {
  root,
  target,
} = require('../config')
const {
  regexAtlas,
  regexSkeleton,
  regexName,
} = require('../config/regConfig')
const readAndMatch = require('../../util/readAndMatch')
const createFoldersAndFiles = require('../script/createFoldersAndFiles')
const getFilesStartingWith = require('../../util/getFilesStartingWith')
const copyAndRenameFiles = require('../script/copyAndRenameFiles')

// 所有模型名字
const nameList = []
// 所有材质缓存
const atlasMap = new Map()
// 材质中的切分图缓存
const atlasAttachmentMap = new Map()
// 所有json缓存
const skeletonMap = new Map()
// 未命名的计数器
let unnamedCount = 0

function getModuleNormalV1() {
  const filePath = path.join(root, getFilesStartingWith(root, 'vendors').pop())
  const imagesRoot = path.join(root, 'images')

  // 拿到所有材质
  const atlasDatas = readAndMatch(filePath, regexAtlas)
  // 拿到所有json
  const skeletonDatas = readAndMatch(filePath, regexSkeleton)

  const modules = []
  const errList = []

  const nameReg = new RegExp(regexName)
  // 准备输出文件夹
  if (!fs.existsSync(target) || !fs.lstatSync(target).isDirectory()) {
    fs.mkdirSync(target)
  }
  console.log('开始拆解文件……')

  atlasDatas.forEach(atlasData => {
    try {
      const atlasText = atlasData.slice(13, -2)
      const fileNameMatch = atlasData.match(nameReg)
      const fileName = fileNameMatch[0].slice(13, -4)
      if (nameList.includes(fileName)) {
        return
      }
      nameList.push(fileName)
      atlasMap.set(fileName, atlasText)
      console.log(atlasText)
      console.log(atlasText.split('\\n'))
      const attachments = atlasText.split('\\n').filter(line => !line.includes(',') && !line.includes('.') && !line.includes(':')).map(item => item.split('/').pop())
      atlasAttachmentMap.set(fileName, attachments)
    } catch (e) {
      console.error(e)
      logger.error(e)
    }
  })

  skeletonDatas.forEach(skeletonData => {
    try {
      const skeletonText = skeletonData.slice(24, -3)
      const skeletonJson = JSON.parse(skeletonText)
      const attachments = skeletonJson.skins[0].attachments
      const attachmentNames = Object.keys(attachments)
      let maxAttachmentsName = ''
      let maxAttachmentsCount = 0
      for (const name of nameList) {
        const attachmentSet = new Set(atlasAttachmentMap.get(name))
        const commonAttachments = attachmentNames.filter(a => attachmentSet.has(a))
        if (commonAttachments.length > maxAttachmentsCount) {
          maxAttachmentsCount = commonAttachments.length
          maxAttachmentsName = name
        }
      }
      if (maxAttachmentsCount === 0) {
        maxAttachmentsName = `未命名_${unnamedCount++}`
        nameList.push(maxAttachmentsName)
      }
      skeletonMap.set(maxAttachmentsName, skeletonText)
    } catch (e) {
      console.error(e)
      logger.error(e)
    }
  })

  nameList.forEach(name => {
    try {
      const atlasText = atlasMap.get(name)
      const skeletonText = skeletonMap.get(name)
      createFoldersAndFiles(target, name, skeletonText, atlasText)
      modules.push(name)
    } catch (e) {
      errList.push(name)
      console.error(`创建文件夹和文件失败：${name}`, e)
      logger.error(`创建文件夹和文件失败：${name}`, e)
    }
  })

  nameList.forEach(name => {
    try {
      copyAndRenameFiles(imagesRoot, target, [name])
    } catch (e) {
      console.error(`复制和重命名文件失败：${name}`, e)
      logger.error(`复制和重命名文件失败：${name}`, e)
    }
  })

  console.log('拆解模型列表完成', modules)
  logger.info('拆解模型列表完成', modules)
  if (errList && errList.length) {
    console.error('部分拆解模型列表失败', errList)
    logger.error('部分拆解模型列表失败', errList)
    return false
  } else {
    return true
  }
}

module.exports = getModuleNormalV1
